const path = require("path");
const fs = require("fs").promises;
class File {
  constructor() {
    this.directory = path.resolve(__dirname, "../../") + "\\hiprintStorage";
  }

  async init() {
    console.log("文件夹File初始化");
    await this.operationDirectory();
  }

  //判断目录和文件是否存在
  isFileExisted(path_way) {
    return new Promise((resolve, reject) => {
      fs.access(path_way, (err) => {
        if (err) {
          resolve(false);
        } else {
          resolve(true);
        }
      });
    });
  }

  //操作目录和文件
  async operationDirectory() {
    //判断目录是否存在
    let isDirectory = await this.isFileExisted(this.directory);
    // console.log("目录是否存在", isDirectory);
    if (!isDirectory) {
      //没有目录，创建
      // 创建文件夹
      let mkdirRes = await fs.mkdir(this.directory);
      // console.log("创建文件夹", mkdirRes);
      this.initConfig(this.directory + "\\config.txt");
    } else {
      //   await this.writeInAppend(this.directory + "\\log.txt");
      //   await this.writeInNoAppend(this.directory + "\\printer.txt");
      this.initConfig(this.directory + "\\config.txt");
    }
  }

  //创建文件，无限追加
  writeIninfiniteAppend(path_way, fileData = "") {
    return new Promise(async (resolve, reject) => {
      let res = await this.isFileExisted(path_way);
      // console.log("文件是否存在", res);
      if (!res) {
        fileData != "" &&
          (await fs.writeFile(path_way, JSON.stringify(fileData)));
      } else if (fileData != "") {
        // 读取文件内容
        let readData = await fs.readFile(path_way, "utf-8");
        let copyData;
        if (readData != "") {
          copyData = JSON.parse(readData);
          copyData = [...copyData, ...fileData];
        } else {
          copyData = [...fileData];
        }
        // //给文件追加内容
        let writeRes = await fs.writeFile(path_way, JSON.stringify(copyData));
        // console.log(`追加写入成功${path_way}`);
      }
      resolve();
    });
  }

  //创建文件，追加类型，10条数据
  writeInAppend(path_way, fileData = "") {
    return new Promise(async (resolve, reject) => {
      let res = await this.isFileExisted(path_way);
      // console.log("文件是否存在", res);
      if (!res) {
        fileData != "" &&
          (await fs.writeFile(path_way, JSON.stringify([fileData])));
      } else if (fileData != "") {
        // 读取文件内容
        let readData = await fs.readFile(path_way, "utf-8");
        // console.log("读取内容");
        let copyData;
        if (readData != "") {
          copyData = JSON.parse(readData);
          if (copyData.length == 10) {
            copyData.shift();
          }
          copyData.push(fileData);
        } else {
          copyData = [fileData];
        }

        // //给文件追加内容
        let writeRes = await fs.writeFile(path_way, JSON.stringify(copyData));
        // console.log("追加写入返回", writeRes);
      }
      resolve();
    });
  }

  //创建文件，不追加类型
  writeInNoAppend(path_way, fileData = "") {
    return new Promise(async (resolve, reject) => {
      let res = await this.isFileExisted(path_way);
      // console.log("文件是否存在", res);
      if (!res) {
        fileData != "" &&
          (await fs.writeFile(path_way, JSON.stringify(fileData)));
      } else if (fileData != "") {
        //写入数据
        let writeRes = await fs.writeFile(path_way, JSON.stringify(fileData));
        // console.log("写入数据成功");
      }
      resolve();
    });
  }

  //读取数据
  readFileFn(path_way) {
    return new Promise(async (resolve, reject) => {
      let data = "";
      let res = await this.isFileExisted(path_way);

      if (res) {
        let readData = await fs.readFile(path_way, "utf-8");
        if (readData != "") {
          data = JSON.parse(readData);
        } else {
          data = "";
        }
      }
      // console.log("开始读取");
      resolve(data);
    });
  }

  //初始config
  initConfig(path_way) {
    return new Promise(async (resolve, reject) => {
      let res = await this.isFileExisted(path_way);
      // console.log("文件是否存在", res);
      let fileData = {
        host: "",
        port: "",
        templateTime: "",
      };
      if (!res) {
        await fs.writeFile(path_way, JSON.stringify(fileData));
      } else {
        let res = await this.readFileFn(path_way);
        if (res == "") {
          await fs.writeFile(path_way, JSON.stringify(fileData));
        }
      }
      resolve();
    });
  }

  //根据key读取config
  getConfigItem(key) {
    return new Promise(async (resolve, reject) => {
      let configObj = await this.readFileFn(this.directory + "\\config.txt");
      // console.log("读1", configObj[key]);
      resolve(configObj[key]);
    });
  }

  //根据key设置config
  setConfigItem(key, val) {
    return new Promise(async (resolve, reject) => {
      let configObj = await this.readFileFn(this.directory + "\\config.txt");
      console.log("设置1", key, val);
      console.log("设置2", configObj);
      configObj[key] = val;
      this.writeInNoAppend(this.directory + "\\config.txt", configObj);
      resolve();
    });
  }

  //删除文件
  unlink(path_way) {
    return new Promise(async (resolve, reject) => {
      let res = await this.isFileExisted(path_way);
      // console.log("文件是否存在,存在需要删除", res);
      if (res) {
        let unlinkRes = await fs.unlink(path_way);
        // console.log("删除成功", unlinkRes);
      }

      resolve();
    });
  }
}

let fileObj = new File();
// fileObj.init();

module.exports = { fileObj };
